# -*- coding: utf-8 -*-
# Create your views here.
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import *
from django.template import Context, loader
from models import *

def generateOrders(request, id):
    from django.contrib.admin.views import main
    main.change_stage(request, 'frontend', 'invoice', id)
    inv = Invoice.objects.get(pk = id)
    if inv.exploded > 0:
	return HttpResponseRedirect('/frontend/order/') 
    
    inv.generateOrders()
   
    return HttpResponseRedirect('/frontend/order/')


def y(y):
    from reportlab.lib.pagesizes import *
    return A4[1]-y

from reportlab.platypus import PageTemplate, \
     BaseDocTemplate, Frame, Paragraph
from reportlab.lib.units import inch, cm
from reportlab.rl_config import defaultPageSize


    
from reportlab.pdfgen import canvas
from reportlab.platypus.tables import *
from reportlab.pdfgen import textobject
from reportlab.lib.units import *
  
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics     
from reportlab.lib.pagesizes import *                                    
from reportlab.pdfbase.ttfonts import TTFont                                   
from reportlab.platypus import *
from reportlab.lib.styles import *
from crm.settings import CONTACT_INFORMATION    

class PdfResponse():
    
    layout = landscape(A4);
    
    def __init__(self, response):
        self.responce = response
        self.story = []
        self.doc = SimpleDocTemplate(response, pagesize=self.layout)
        pdfmetrics.registerFont(TTFont('XArial', 'arial.ttf')) 

    def paraLeft(self, text):
        self.para(text, ParagraphStyle('description',
                                fontName='XArial',
                                fontSize=10,
                                alignment = 0,
                                leading=9.6))
    def para(self, text, style):
        
        para = Paragraph(text, style)
        
        self.story.append(para)
        
    def spacer(self):
        self.story.append(Spacer(1*cm, 1*cm))
        
    def build(self):
        return self.doc.build(self.story)
    
    def add(self, item):
        self.story.append(item)
        
class PdfOrderResponse(PdfResponse):
    
    layout = landscape(A5)
    
    def __init__(self, response):
        PdfResponse.__init__(self, response)
         

def generateInvoicePDF(request, id):  
                                                                                  
    
    from django.contrib.admin.views import main
    main.change_stage(request, 'frontend', 'invoice', id)
        
    response = HttpResponse(mimetype='application/pdf')
    #response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'
    

    invoice = Invoice.objects.get(pk = id)
    render = PdfResponse(response)
    render.paraLeft(u"""<para>Внимание!!! <i>Информация</i> о готовности заказа поступет после 9-00.
                                            <u>Телефон: 66-41-68, 66-45-53, 66-4-68 Ирина</u> </para>""")
    render.spacer()
    date = invoice.dateCreate.__str__();
    render.para(u"Расчет кровельных материалов", ParagraphStyle('description',
                                fontName='XArial',
                                fontSize=11,
                                alignment = 0,
                                leading=9.6)) 
    render.paraLeft(u"Счет №: %s от %s" % (invoice.id, date[0:10]))      
    render.paraLeft(u"Заказчик: %s" % invoice.client.orgName)
    render.paraLeft(u"Адрес: %s" % invoice.client.address1)
    render.paraLeft(u"Телефон: %s %s %s" % (invoice.client.phone1, invoice.client.phone2, invoice.client.fax) )    
  
    render.paraLeft("Привязанные заказы")
    for order in invoice.getOrders():
         render.paraLeft(u"#%s (%s)" % (order.id, order.workshop.name)) 
    render.spacer()
    data = [["#",
             "Наиминование",
             "Длина (м)",
             "Ширина (м)",
             "Цвет",
             "Пл. листа (кв. м)",
             "Кол-во (шт)", 
             "Общая пл. (кв. м)",
             "Цена за ед. (р)",
             "Цена листа",         
             "Всего (р)"]            
            ]
    i = 0;
    for item in invoice.invoiceitem_set.all():
     
        c = ''
        if item.width and item.height:
           c = item.width * item.height
        sum = item.quantity * item.price
        color = ""
        if item.color: 
            color = item.color.__unicode__()
	i = i + 1
	pName = Paragraph(item.__unicode__() ,
				ParagraphStyle('description',
				fontName='XArial',
				fontSize=7,
				alignment = 0,
				leading=9.6))
	pColor = Paragraph(color ,
				ParagraphStyle('description',
				fontName='XArial',
				fontSize=7,
				alignment = 0,
				leading=9.6))

        data.append([i,
                      pName,
                      item.height,
                      item.width,
                      pColor,
                      item.itemarea,
                      item.quantity,
                      item.totalarea,
                      item.price,
                      
                      item.areaprice,
                     
                      item.total])
         
    data.append(['','','','','','','','','','Итого:',"%d" % round(invoice.sum)])    
    
    t = Table(data, colWidths = [1*cm, 4*cm,2*cm,2*cm, 3*cm, 2.4*cm,2.4*cm,2.4*cm,2.4*cm,2.4*cm,2.4*cm,])
    t.bottomoup = 1
    table_style = TableStyle()
    table_style.add('FONTNAME', (0,0), (-1,-1), 'XArial')
    table_style.add('VALIGN', (0,0), (-1,-1), 'TOP')
    table_style.add('FONTSIZE', (0,0), (-1,-1), 7)
    table_style.add('GRID', (0,0), (-1,-2), 1, colors.gray)
    table_style.add('BACKGROUND', (0,0), (-1,0), colors.Color(0.9,0.9,0.9))
    table_style.add('BACKGROUND', (-1,-1), (-1,-1), colors.Color(0.9,0.9,0.9))
    t.setStyle(table_style)    
    render.add(t)
    render.spacer()
    render.paraLeft(u"С условием хранения и транспортировки ознакомлен ____________________(подпись закзачика)")
    render.spacer()
    render.paraLeft(u"Срок хранения заказа на складе три дня со дня изготовления. За каждый полседующий день взимается плата в размере 200 руб. в день")
    render.paraLeft(u"Срок хранения доборных элементов со дня изготовления 10 календарных дней, после чего фирма оставлет право его реализовать без возрата денег клиенту")
    
    
    
    render.para(u"<para><u><b>Бесплатная погрузка только в открытую машину. Погрузка в закрытую машину платная</b></u></para>", ParagraphStyle('description',
                                fontName='XArial',
                                fontSize=14,
                                alignment = 0,
                                leading=9.6))
    render.spacer()
    render.para(u"С условиями Заказа согласен ____________ Заказ принял _____________", ParagraphStyle('description',
                                fontName='XArial',
                                fontSize=10,
                                alignment = 1,
                                leading=9.6))
    render.build()
    return response
    
    
def generateOrderPDF(request, id):  
                                                                                  
   
    from django.contrib.admin.views import main
    main.change_stage(request, 'frontend', 'order', id)
    response = HttpResponse(mimetype='application/pdf')
    #response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'
    

    order = Order.objects.get(pk = id)
    render = PdfOrderResponse(response)
    render.paraLeft(u"Заказ : %s" % order.id)
    render.paraLeft("Счет: %s (%s)" % (order.invoice.id , order.invoice.manager))
    if(order.workshop):       
        render.paraLeft(u"Цех: %s" % order.workshop.name)
    from time import * 
    render.paraLeft(u"Дата: %s" % strftime("%d-%m-%Y", 
                strptime(order.dateCreate.__str__(), "%Y-%m-%d %H:%M:%S"))
                )    
    render.spacer()
    
    
    data = [["#", "Код", "Цвет", "Длина (мм)", "Толщина (мм)", "Погонаж (мм)", "Количество"]            
            ]
    i = 0;

    for item in order.orderitem_set.order_by('code', 'color'):
        c = ''
        if not item.item.code :
            name = item.item.name
        else :
            name = item.item.code
        p = Paragraph(name, ParagraphStyle('description',
                                fontName='XArial',
                                fontSize=9,
                                alignment = 1,
                                leading=9.6))
        #if item.width and item.height:
        #   c = item.width * item.height
        color = ""
        pcolor = ""
        if item.color: 
            import re
            pattern = re.compile("\((.*)\)")
            color = pattern.findall(item.color.__unicode__())[0]
        if color:
            pcolor = color
        data.append([i + 1, p, pcolor, item.height, item.item.thick,  item.pogonag, item.quantity])         
        
    t = Table(data, colWidths = [1.5*cm, 3.5*cm, 2.5*cm, 2.5*cm,2.5*cm,  2.5*cm, 2.5*cm])
    t.bottomoup = 1
    table_style = TableStyle()
    table_style.add('FONTNAME', (0,0), (-1,-1), 'XArial')
    table_style.add('FONTSIZE', (0,0), (-1,-1), 9)
    table_style.add('BACKGROUND', (0,0), (-1,0), colors.Color(0.9,0.9,0.9))
    table_style.add('GRID', (0,0), (-1,-1), 1, colors.gray)
    t.setStyle(table_style)    
    render.add(t)
    render.spacer()
    
    render.paraLeft(order.comment)
    render.paraLeft("Сдал _________________")
    render.paraLeft("Принял _________________")
    render.spacer()
    render.paraLeft(CONTACT_INFORMATION)
    render.build()
    return response
